package rpc.netcon.jetty.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc.codec.HessianSerializer;
import rpc.netcon.HttpClientUtil;
import rpc.netcon.RpcResponse;
import rpc.netcon.RpcRequest;

/**
 * Created by zhangyanfei on 2018/10/11.
 *
 * @author zhangyanfei
 * @date 2018/10/11
 */
public class JettyClient {
    private static Logger logger = LoggerFactory.getLogger(JettyClient.class);

    public RpcResponse send(RpcRequest request) {
        try {
            // 1.序列化请求
            byte[] requestBytes = HessianSerializer.serialize(request);

            // 2.请求地址
            String reqURL = request.getServerAddress();
            if (reqURL != null && reqURL.toLowerCase().indexOf("http") == -1) {
                reqURL = "http://" + request.getServerAddress() + "/";    // IP:PORT, need parse to url
            }

            // 3.远程调用
            byte[] responseBytes = HttpClientUtil.postRequest(reqURL, requestBytes);
            if (responseBytes == null || responseBytes.length == 0) {
                RpcResponse rpcResponse = new RpcResponse();
                rpcResponse.setError("Network request fail, RpcResponse byte[] is null");
                return rpcResponse;
            }

            // 4.反序列化结果
            RpcResponse rpcResponse = (RpcResponse)HessianSerializer.deserialize(responseBytes, RpcResponse.class);
            return rpcResponse;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);

            RpcResponse rpcResponse = new RpcResponse();
            rpcResponse.setError("Network request error: " + e.getMessage());
            return rpcResponse;
        }
    }
}
